package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.dialog.ECAlertDialog;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.LoginResult;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.http.HttpStatusUtil;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.util.recoder.AudioRecoderDialog;
import com.yuntongxun.ecdemo.voicechat.util.recoder.AudioRecoderUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 个人信息 /包含个人信息，别人信息
 *
 * @author li_zhuonan
 * @version 1.0
 * @since 2016/11/22
 */

public class InfoActivity extends BaseChatActivity implements ICommonViewUi, AudioRecoderUtils.OnAudioStatusUpdateListener {
    /**
     * 来源
     */
    public static final String FROM = "from";
    public static final String MYSELF = "myself";
    public static final String OTHERS = "others";
    /**
     * 账号
     */
    public static final String ACCOUNT = "account";
    @InjectView(R.id.nameTv)
    TextView nameTv;
    @InjectView(R.id.gendeImg)
    ImageView gendeImg;
    @InjectView(R.id.ageTv)
    TextView ageTv;
    @InjectView(R.id.countryImg)
    ImageView countryImg;
    @InjectView(R.id.nativeTv)
    TextView nativeTv;
    @InjectView(R.id.introductionTv)
    TextView introductionTv;
    @InjectView(R.id.block_btn)
    CardView blockBtn;
    @InjectView(R.id.report_btn)
    CardView reportBtn;
    @InjectView(R.id.hear_me_btn)
    CardView hearMeBtn;
    @InjectView(R.id.learnTv1)
    TextView learnTv1;
    @InjectView(R.id.learnTv2)
    TextView learnTv2;
    @InjectView(R.id.learnTv3)
    TextView learnTv3;
    @InjectView(R.id.learnTv4)
    TextView learnTv4;


    //录制声音
    @OnClick(R.id.recoder_layout_bg)
    public void onBgClick(){

    }
    @InjectView(R.id.recoder_close_btn)
    ImageView closeBtn;
    @InjectView(R.id.recoderBtn)
    ImageView recoderBtn;
    @InjectView(R.id.recoder_layout)
    RelativeLayout recoderLayout;
    private String accountName = "";

    @InjectView(R.id.voice_layout)
    LinearLayout voiceLayout;

    private ICommonRequestPresenter iCommonRequestPresenter;

    private ECProgressDialog mPostingdialog;

    private TextView[] learnTvs;

    private AudioRecoderDialog recoderDialog;
    private AudioRecoderUtils recoderUtils;
    private long downT;
    EditText fileNameEdt;

    MediaPlayer mediaPlayer;

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    public void onEvent(PostResult postResult) {
        if (EventBusTags.UPDATE_INFO.equals(postResult.getTag())) {
            if (userInfo != null) {
                accountName = userInfo.getAccountName();
                toRequest(ApiConstants.EventTags.USER_INFO);
            }

        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_info;
    }

    UserInfo userInfo;
    String filePath = "";

    private boolean isMySelf = false;

    @Override
    protected void initViewsAndEvents() {
        setTitle("Profile");

        recoderDialog = new AudioRecoderDialog(this);
        mediaPlayer=new MediaPlayer();
//        recoderDialog.setShowAlpha(0.98f);
        filePath = Environment.getExternalStorageDirectory() + "/recoder.amr";
        recoderUtils = new AudioRecoderUtils(new File(filePath));
        recoderUtils.setOnAudioStatusUpdateListener(this);

        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);
        learnTvs = new TextView[]{learnTv1, learnTv2, learnTv3, learnTv4};

        if (getIntent().getStringExtra(FROM).equals(MYSELF)) {
            isMySelf = true;

            initMyUI();
            accountName = getIntent().getStringExtra(ACCOUNT);
            String data = PreferenceUtils.getPrefString(this, Contants.Preference.user_info, "");
            if (!data.equals("")) {
                JsonHelper<UserInfo> jsonHelper = new JsonHelper<UserInfo>(UserInfo.class);
                userInfo = jsonHelper.getData(data, "result");
                bindData(userInfo);
            }
        } else {
            isMySelf = false;

            String userId = getIntent().getStringExtra(ACCOUNT);
            ArrayList<ECContacts> contacts = ContactSqlManager.getContacts();
            for (int i=0;i< contacts.size();i++){
                if (userId.equals(contacts.get(i).getContactid())){
                    String nickName=contacts.get(i).getNickname();
                    if (nickName.contains("(")){
                        int index=nickName.indexOf("(");
                        String message=nickName.substring(index+1,nickName.length()-1);
                        JsonHelper<UserInfo> dataParser = new JsonHelper<UserInfo>(
                                UserInfo.class);
                        UserInfo info= dataParser.getData(
                                message, "result");
                        if (info!=null){
                            accountName=info.getAccountName();
                            LogUtil.e("accountName",accountName);
                        }
                        break;
                    }
//                    int index=nickName.indexOf("(");
//                    if (index!=-1){
//                        accountName=nickName.substring(0,index);
//                        Log.e("accountName",accountName);
//                    }

                }
            }
            initOthersUI();
            toRequest(ApiConstants.EventTags.USER_INFO);
        }


        recoderBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        recoderUtils.startRecord();
                        downT = System.currentTimeMillis();
                        recoderDialog.showAtLocation(view, Gravity.CENTER, 0, 0);
                        return true;
                    case MotionEvent.ACTION_UP:
                        recoderUtils.stopRecord();
                        recoderDialog.dismiss();
                        recoderLayout.setVisibility(View.GONE);
                        showDialog();
                        return true;
                }
                return false;
            }
        });

    }
    ECAlertDialog buildAlert;
    private void showDialog() {
        fileNameEdt=new EditText(this);
        fileNameEdt.setHint("Please enter the file name");
        buildAlert = ECAlertDialog.buildAlert(mContext, "Are you sure you want to upload to the web?",
                "No", "Sure", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        try {
                            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);
                            field.set(dialog, true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        dialog.dismiss();


                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.isEmpty(fileNameEdt.getText().toString().trim())){
                            ToastUtil.showMessage("Please enter the file name");
                            return;
                        }
                        toRequest(ApiConstants.EventTags.UPLOAD_FILE);
                    }
                });
        buildAlert.setTitle("Title");
        buildAlert.setContentView(fileNameEdt);
        buildAlert.setCanceledOnTouchOutside(false);
        buildAlert.show();

        try {
            Field field = buildAlert.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(buildAlert, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @InjectView(R.id.name_layout)
    LinearLayout nameLayout;

    @InjectView(R.id.languageLayout)
    LinearLayout languageLayout;

    @InjectView(R.id.introductionLayout)
    LinearLayout introductionLayout;


    private void initMyUI() {
        blockBtn.setVisibility(View.GONE);
        reportBtn.setVisibility(View.GONE);
        nameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(InfoActivity.this, EditInfoActivity.class);
                startActivity(intent);
            }
        });

        languageLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(InfoActivity.this, EditLanguagesActivity.class);
                startActivity(intent);
            }
        });

        introductionLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(InfoActivity.this, EditSelfIntroductionActivity.class);
                startActivity(intent);
            }
        });

    }

    private void initOthersUI() {
        setRightTitle("Follow");
        hearMeBtn.setVisibility(View.GONE);
    }

    @OnClick({R.id.toolbar_right_title,R.id.recoder_close_btn,R.id.hear_me_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_right_title:
                toRequest(ApiConstants.EventTags.FOLLOW);
                break;
            case R.id.recoder_close_btn:
                recoderLayout.setVisibility(View.GONE);
                break;
            case R.id.hear_me_btn:
                recoderLayout.setVisibility(View.VISIBLE);
                break;

        }
    }

    @Override
    public void toRequest(int eventTag) {
        switch (eventTag) {
            case ApiConstants.EventTags.FOLLOW:
                RequestParams map = new RequestParams();
                map.put("friendAccount", accountName);
                iCommonRequestPresenter.request(ApiConstants.EventTags.FOLLOW, mContext, ApiConstants.Urls.FOLLOW, map);
                break;
            case ApiConstants.EventTags.USER_INFO:
                map = new RequestParams();
                map.put("accountName", accountName);
                iCommonRequestPresenter.request(ApiConstants.EventTags.USER_INFO, mContext, ApiConstants.Urls.ACCOUNT_INFO, map);
                break;
            case ApiConstants.EventTags.UPLOAD_FILE:
                map=new RequestParams();
                map.put("name", fileNameEdt.getText().toString().trim());
                File file=new File(filePath);
                File[] files={file};
                try {
                    map.put("files", files);
                    map.setForceMultipartEntityContentType(true);
                    iCommonRequestPresenter.request(ApiConstants.EventTags.UPLOAD_FILE, mContext, ApiConstants.Urls.VOICE_ADD, map);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                break;

        }
    }

    UserInfo currentUserInfo;

    @Override
    public void getRequestData(int eventTag, String result) {
        switch (eventTag) {
            case ApiConstants.EventTags.FOLLOW:
                showToastLong(HttpStatusUtil.getStatusMsg(result));
                break;
            case ApiConstants.EventTags.USER_INFO:

                JsonHelper<UserInfo> jsonHelper = new JsonHelper<UserInfo>(UserInfo.class);
                currentUserInfo = jsonHelper.getData(result, "result");
                if (currentUserInfo != null) {
                    bindData(currentUserInfo);
                    if (userInfo != null) {
                        if (userInfo.getAccountName().equals(currentUserInfo.getAccountName())) {
                            PreferenceUtils.setPrefString(this, Contants.Preference.user_info, result);
                            PostResult postResult = new PostResult();
                            postResult.setTag(EventBusTags.UPDATE_ME);
                            EventBus.getDefault().post(postResult);
                        }
                    }
                }
                break;
            case ApiConstants.EventTags.UPLOAD_FILE:
//                showToastLong(HttpStatusUtil.getStatusMsg(result));
                if (buildAlert!=null){
                    if (userInfo != null) {
                        accountName = userInfo.getAccountName();
                        toRequest(ApiConstants.EventTags.USER_INFO);
                    }

                    try {
                        Field field = buildAlert.getClass().getSuperclass().getDeclaredField("mShowing");
                        field.setAccessible(true);
                        field.set(buildAlert, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    buildAlert.dismiss();
                }

                break;
            case ApiConstants.EventTags.DELETE_VOICE:
                //删除语音
                showToastShort("delete success");

                userInfo.getVoiceList().remove(deletePosition);

                bindData(userInfo);

                LoginResult loginResult = new LoginResult();
                loginResult.setResult(userInfo);

                String json = new Gson().toJson(loginResult);

                PreferenceUtils.setPrefString(mContext, Contants.Preference.user_info, json);

                break;
        }
    }

//    View voiceView;
//    TextView voiceNameTv,voiceTimeTv;
//    RelativeLayout voiceLayout;
    int voideIndex =0;
    List<TextView> timeTvs=new ArrayList<>();
    private void bindData(final UserInfo userInfo) {

        ECContacts contact = new ECContacts();
//        String message = info.getNickName() + "-" + info.getGender() + "-" + info.getAge() + "-" + info.getCountry() + "-" + info.getNativeLanguage() + "-" + info.getLearningLanguage();
        StringBuffer message= new StringBuffer();
        message.append("{\"result\":" );
        message.append("{\"accountName\":\"" + userInfo.getAccountName() + "\",");
        message.append("\"nickName\":\"" + userInfo.getNickName() + "\",");
        message.append("\"id\":\"" + userInfo.getId() + "\",");
        message.append("\"gender\":\"" + userInfo.getGender() + "\",");
        message.append("\"age\":\"" + userInfo.getAge() + "\",");
        message.append("\"country\":\"" + userInfo.getCountry() + "\",");
        message.append("\"nativeLanguage\":\"" + userInfo.getNativeLanguage() + "\",");
        message.append("\"learningLanguage\":\"" + userInfo.getLearningLanguage() + "\"}}");
        contact.setNickname(userInfo.getNickName() + "(" + message.toString() + ")");
        contact.setContactid(userInfo.getId());
        ContactSqlManager.insertContact(contact);

        this.userInfo = userInfo;

        nameTv.setText(userInfo.getNickName());
        ageTv.setText(userInfo.getAge() + "");
        if (userInfo.getGender().equals("男")){
            gendeImg.setImageResource(R.drawable.ic_man);
        }else{
            gendeImg.setImageResource(R.drawable.ic_woman);
        }

        for (int i = 0; i < learnTvs.length; i++) {
            learnTvs[i].setVisibility(View.GONE);
        }
        try {
            InputStream is = getAssets().open("flag/" + userInfo.getCountry() + ".png");
            countryImg.setImageBitmap(BitmapFactory.decodeStream(is));
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        nativeTv.setText(userInfo.getNativeLanguage());
        introductionTv.setText(userInfo.getTextDescription());

        String learnLanguages = userInfo.getLearningLanguage();
        if (learnLanguages != null && !learnLanguages.equals("")) {
            String[] languages = learnLanguages.split(",");
            for (int i = 0; i < languages.length; i++) {
                learnTvs[i].setText(languages[i]);
                learnTvs[i].setVisibility(View.VISIBLE);
            }
        }
        voiceLayout.removeAllViews();
        if (userInfo.getVoiceList()!=null&&userInfo.getVoiceList().size()>0){
            for (int i=0;i<userInfo.getVoiceList().size();i++){
                View voiceView =getLayoutInflater().inflate(R.layout.adapter_voice_item,null);
                TextView voiceNameTv=(TextView)voiceView.findViewById(R.id.voice_item_name);
                TextView voiceTimeTv=(TextView)voiceView.findViewById(R.id.voice_item_time);
                ImageView deleteVoieBtn =(ImageView)voiceView.findViewById(R.id.delete_voice_btn);
                if(isMySelf){
                    deleteVoieBtn.setVisibility(View.VISIBLE);
                }else{
                    deleteVoieBtn.setVisibility(View.GONE);
                }
                RelativeLayout voiceItemLayout=(RelativeLayout)voiceView.findViewById(R.id.voice_item_layout);
                voiceNameTv.setText(userInfo.getVoiceList().get(i).getName());
                timeTvs.add(voiceTimeTv);
                voiceLayout.addView(voiceView);
                voideIndex =i;
                voiceItemLayout.setOnClickListener(new onVoiceItemClick(voideIndex));
                deleteVoieBtn.setOnClickListener(new onLongVoiceItemClick(voideIndex));
                new VoiceThread(i,userInfo).start();//启动线程获取时长
            }
        }

    }

    private class VoiceThread extends Thread{
        int position;
        UserInfo userInfo;
        public VoiceThread(int position,UserInfo userInfo){
            this.position=position;
            this.userInfo=userInfo;
        }

        @Override
        public void run() {
            super.run();
            try {
                MediaPlayer mediaPlayer=new MediaPlayer();
                mediaPlayer
                        .setDataSource(userInfo.getVoiceList().get(position).getVoice());
                mediaPlayer.prepare();
                int time=(int)Math.ceil(mediaPlayer.getDuration()/1000);
                Message msg=Message.obtain();
                msg.what=1;
                msg.obj=position+"-"+time;
                myHandler.sendMessage(msg);
                mediaPlayer.release();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    VoiceHandler myHandler=new VoiceHandler();
    private class VoiceHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String[] test=msg.obj.toString().split("-");
            timeTvs.get(Integer.parseInt(test[0])).setText(test[1]+"'");

        }
    }

    private class onVoiceItemClick implements View.OnClickListener{

        int position=0;
        public onVoiceItemClick(int position){
            this.position=position;
        }


        @Override
        public void onClick(View v) {
            if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
                mediaPlayer.stop();
            }
            mediaPlayer=new MediaPlayer();
            try {
                if (userInfo!=null){
                    mediaPlayer
                            .setDataSource(userInfo.getVoiceList().get(position).getVoice());
                }else{
                    mediaPlayer
                            .setDataSource(currentUserInfo.getVoiceList().get(position).getVoice());
                }
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start();
                    }
                });
            } catch (IOException e) {
                Log.v("AUDIOHTTPPLAYER", e.getMessage());
            }
        }
    }

    /**
     * 长按语音删除
     */
    int deletePosition=0;
    private class onLongVoiceItemClick implements View.OnClickListener{


        public onLongVoiceItemClick(int position){
            deletePosition=position;
        }

        @Override
        public void onClick(View v) {

            ECAlertDialog buildAlert = ECAlertDialog.buildAlert(InfoActivity.this, R.string.delete_voice, null, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    RequestParams params = new RequestParams();
                    params.put("id", "" + userInfo.getVoiceList().get(deletePosition).getId());

                    iCommonRequestPresenter.request(ApiConstants.EventTags.DELETE_VOICE, mContext, ApiConstants.Urls.DELETE_VOICE, params);
                }

            });
            buildAlert.setTitle("   ");
            buildAlert.show();
        }
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        showToastLong(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        showToastLong(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        //账号登录
        if (status) {
            mPostingdialog = new ECProgressDialog(this, "Waiting");
            mPostingdialog.show();
        } else {
            mPostingdialog.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (recoderLayout.getVisibility()==View.VISIBLE){
                recoderLayout.setVisibility(View.GONE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onUpdate(double db) {
        if (null != recoderDialog) {
            int level = (int) db;
            recoderDialog.setLevel((int) db);
            recoderDialog.setTime(System.currentTimeMillis() - downT);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer!=null){
            mediaPlayer.release();
        }
    }

    @OnClick(R.id.report_btn)
    public void onReportBtnClick(){
        Intent intent=new Intent(this,ReportActivity.class);
        intent.putExtra(ReportActivity.REPORTACCOUNT,accountName);
        startActivity(intent);
    }
}
